<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Centos 配置 PHP memcached 缓存【踩坑】 | 指尖改变世界</title><meta name="keywords" content="memcached"><meta name="author" content="沙屿沫"><meta name="copyright" content="沙屿沫"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="最近项目中，刚好配置一个新的服务器 memcache 环境。项目中用到 memcache 缓存的时候，需要先在服务器上安装 memcache 环境，以及配置 PHP 的 memcache 拓展。目前接触到使用 memcache 缓存的场景是，多终端登录，前后端分离，设置登录 session 值。 安装教程，可以参考阿里云官方文档。  https:&#x2F;&#x2F;help.aliyun.com&#x2F;document">
<meta property="og:type" content="article">
<meta property="og:title" content="Centos 配置 PHP memcached 缓存【踩坑】">
<meta property="og:url" content="http://blog.shayvmo.cn/2019/08/30/memcache/index.html">
<meta property="og:site_name" content="指尖改变世界">
<meta property="og:description" content="最近项目中，刚好配置一个新的服务器 memcache 环境。项目中用到 memcache 缓存的时候，需要先在服务器上安装 memcache 环境，以及配置 PHP 的 memcache 拓展。目前接触到使用 memcache 缓存的场景是，多终端登录，前后端分离，设置登录 session 值。 安装教程，可以参考阿里云官方文档。  https:&#x2F;&#x2F;help.aliyun.com&#x2F;document">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.shayvmo.cn/images/7e3483ec4f7dedd5a30f0e7fee1635b921.png">
<meta property="article:published_time" content="2019-08-30T15:10:48.000Z">
<meta property="article:modified_time" content="2022-08-23T09:51:45.108Z">
<meta property="article:author" content="沙屿沫">
<meta property="article:tag" content="memcached">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.shayvmo.cn/images/7e3483ec4f7dedd5a30f0e7fee1635b921.png"><link rel="shortcut icon" href="/images/avatar.jpg"><link rel="canonical" href="http://blog.shayvmo.cn/2019/08/30/memcache/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?5e4d1e8fcc524b4e732ea58fa9fa15f0";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Centos 配置 PHP memcached 缓存【踩坑】',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-08-23 17:51:45'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/images/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">74</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">42</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/images/7e3483ec4f7dedd5a30f0e7fee1635b921.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">指尖改变世界</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Centos 配置 PHP memcached 缓存【踩坑】</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-08-30T15:10:48.000Z" title="发表于 2019-08-30 23:10:48">2019-08-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-08-23T09:51:45.108Z" title="更新于 2022-08-23 17:51:45">2022-08-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Memcached/">Memcached</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Centos 配置 PHP memcached 缓存【踩坑】"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>最近项目中，刚好配置一个新的服务器 memcache 环境。<br>项目中用到 memcache 缓存的时候，需要先在服务器上安装 memcache 环境，以及配置 PHP 的 memcache 拓展。<br>目前接触到使用 memcache 缓存的场景是，多终端登录，前后端分离，设置登录 session 值。</p>
<p>安装教程，可以参考阿里云官方文档。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/48432.html?spm=a2c4g.11186623.6.564.4a1a7cc53z7YxM">https://help.aliyun.com/document_detail/48432.html?spm=a2c4g.11186623.6.564.4a1a7cc53z7YxM</a></p>
</blockquote>
<p><strong>注： 如果在生产环境的服务器，记得先做备份。</strong></p>
<p>Centos 及 Aliyun Linux 6系列版本</p>
<p>1、确认是否安装了gcc-c++ 等组件（使用 <code>gcc –v</code> 查看版本是否为4.2及以上）。<br>如没有请执行 <code>yum install gcc+ gcc-c++</code>。</p>
<p>2、执行 <code>rpm -qa | grep php</code> 查看系统中是否有 PHP 环境。<br>如果没有则执行 <code>yum install php-devel,php-common,php-cli</code> 安装包含源码编译的 PHP。</p>
<p>3、检测是否有已安装了 SASL 相关环境包，如没有，则执行 yum install cyrus-sasl-plain cyrus-sasl cyrus-sasl-devel cyrus-sasl-lib 安装 SASL 相关环境。</p>
<p>4、检测下是否有已安装了 libmemcached 源码包，若没有，则执行以下命令安装 libmemcached 源码包（推荐版本 libmemcached-1.0.18）。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz </span><br><span class="line"></span><br><span class="line">tar zxvf libmemcached-1.0.18.tar.gz</span><br><span class="line"></span><br><span class="line">cd libmemcached-1.0.18</span><br><span class="line"></span><br><span class="line">./configure --prefix=/usr/local/libmemcached --enable-sasl</span><br><span class="line"></span><br><span class="line">make</span><br><span class="line"></span><br><span class="line">make install</span><br><span class="line"></span><br><span class="line">cd ..</span><br></pre></td></tr></table></figure>

<p>5、执行 yum install zlib-devel 安装 memcached 源码包（推荐版本为 memcached-2.2.0）。<br>注意：<br>1、安装 memcached 前需要确认是否有 zlib-devel 包需要执行。</p>
<p>2、请先检测下是否已安装了 memcached 客户端包（包含源码包）。如有则不需要安装，但需要重新编译增加 -enable-memcached-sasl 这个扩展。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">wget http://pecl.php.net/get/memcached-2.2.0.tgz</span><br><span class="line"></span><br><span class="line">tar zxvf memcached-2.2.0.tgz</span><br><span class="line"></span><br><span class="line">cd memcached-2.2.0</span><br><span class="line"></span><br><span class="line">phpize（如果系统中有两套PHP环境，需绝对路径调用该命令/usr/bin/phpize，该路径为使用云数据库Memcache的PHP环境路径）</span><br><span class="line"></span><br><span class="line">./configure --with-libmemcached-dir=/usr/local/libmemcached --enable-memcached-sasl（注意这个参数）</span><br><span class="line"></span><br><span class="line">make</span><br><span class="line"></span><br><span class="line">make install</span><br></pre></td></tr></table></figure>


<p>6、修改 php.ini 文件（locate 找该文件，如果系统中有两套 PHP 环境，需找到使用云数据库 Memcache 的 PHP 环境路径，对应修改之），<br>末尾增加 </p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extension=memcached.so</span><br><span class="line">memcached.use_sasl = 1</span><br></pre></td></tr></table></figure>


<p>7、使用该页面最后的测试代码测试下是否环境部署成功，请修改代码中相应的地址、端口、用户名及密码。<br>注：新版的阿里云 memcache 服务，账号为实例ID</p>
<hr>
<p>【 PHP实例代码 】</p>
<p>示例1：基本的连接云数据库 Memcache 及 set/get 操作</p>
<figure class="highlight php"><table><tr><td class="code"><pre><span class="line"><span class="variable">$connect</span> = <span class="keyword">new</span> Memcached;  <span class="comment">//声明一个新的memcached链接</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_COMPRESSION, <span class="literal">false</span>); <span class="comment">//关闭压缩功能</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_BINARY_PROTOCOL, <span class="literal">true</span>); <span class="comment">//使用binary二进制协议</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_TCP_NODELAY, <span class="literal">true</span>); <span class="comment">//重要，php memcached有个bug，当get的值不存在，有固定40ms延迟，开启这个参数，可以避免这个bug</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;addServer(<span class="string">&#x27;aaaaaaaaaa.m.yyyyyyyyyyy.ocs.aliyuncs.com&#x27;</span>, <span class="number">11211</span>); <span class="comment">//添加OCS实例地址及端口号</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setSaslAuthData(<span class="string">&#x27;aaaaaaaaaa&#x27;</span>, <span class="string">&#x27;password&#x27;</span>); <span class="comment">//设置OCS帐号密码进行鉴权，如已开启免密码功能，则无需此步骤；新版OCS的username为实例id</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;set(<span class="string">&quot;hello&quot;</span>, <span class="string">&quot;world&quot;</span>);</span><br><span class="line"><span class="keyword">echo</span> <span class="string">&#x27;hello: &#x27;</span>,<span class="variable">$connect</span>-&gt;get(<span class="string">&quot;hello&quot;</span>);</span><br><span class="line"><span class="variable">$connect</span>-&gt;quit();</span><br></pre></td></tr></table></figure>


<p>示例2：在云数据库 Memcache 中缓存一个数组</p>
<figure class="highlight php"><table><tr><td class="code"><pre><span class="line"><span class="variable">$connect</span>= <span class="keyword">new</span> Memcached; <span class="comment">//声明一个新的memcached链接</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_COMPRESSION, <span class="literal">false</span>); <span class="comment">//关闭压缩功能</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_BINARY_PROTOCOL, <span class="literal">true</span>);<span class="comment">//使用binary二进制协议</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_TCP_NODELAY, <span class="literal">true</span>); <span class="comment">//重要，php memcached有个bug，当get的值不存在，有固定40ms延迟，开启这个参数，可以避免这个bug</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;addServer(<span class="string">&#x27;xxxxxxxx.m.yyyyyyyy.ocs.aliyuncs.com&#x27;</span>, <span class="number">11211</span>);<span class="comment">//添加OCS实例地址及端口号</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setSaslAuthData(<span class="string">&#x27;xxxxxxxx&#x27;</span>, <span class="string">&#x27;bbbbbbbb&#x27;</span>);<span class="comment">//设置OCS帐号密码进行鉴权，如已开启免密码功能，则无需此步骤</span></span><br><span class="line"><span class="variable">$user</span> = <span class="keyword">array</span>(</span><br><span class="line">    <span class="string">&quot;name&quot;</span> =&gt; <span class="string">&quot;ocs&quot;</span>,</span><br><span class="line">    <span class="string">&quot;age&quot;</span> =&gt; <span class="number">1</span>,</span><br><span class="line">    <span class="string">&quot;sex&quot;</span> =&gt; <span class="string">&quot;male&quot;</span></span><br><span class="line">); <span class="comment">//声明一组数组  </span></span><br><span class="line"><span class="variable">$expire</span> = <span class="number">60</span>; <span class="comment">//设置过期时间</span></span><br><span class="line">test(<span class="variable">$connect</span>-&gt;set(<span class="string">&#x27;your_name&#x27;</span>,<span class="variable">$user</span>,<span class="variable">$expire</span>), <span class="literal">true</span>, <span class="string">&#x27;Set cache failed&#x27;</span>);</span><br><span class="line"><span class="keyword">if</span>(<span class="variable">$connect</span>-&gt;get(<span class="string">&#x27;your_name&#x27;</span>))&#123;</span><br><span class="line"><span class="variable">$result</span> =<span class="variable">$connect</span>-&gt;get(<span class="string">&#x27;your_name&#x27;</span>);</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;  </span><br><span class="line"><span class="keyword">echo</span> <span class="string">&quot;Return code:&quot;</span>, <span class="variable">$connect</span>-&gt;getResultCode();</span><br><span class="line"><span class="keyword">echo</span> <span class="string">&quot;Retucn Message:&quot;</span>, <span class="variable">$connect</span>-&gt;getResultMessage (); <span class="comment">//如出现错误，解析出返回码</span></span><br><span class="line"><span class="variable">$result</span>=<span class="string">&quot; &quot;</span>;</span><br><span class="line">&#125;  </span><br><span class="line">print_r(<span class="variable">$result</span>);</span><br><span class="line"><span class="variable">$connect</span>-&gt;quit();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"><span class="variable">$val</span>, <span class="variable">$expect</span>, <span class="variable">$msg</span></span>)</span></span><br><span class="line"><span class="function"></span>&#123;  </span><br><span class="line">    <span class="keyword">if</span>(<span class="variable">$val</span>!= <span class="variable">$expect</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Exception</span>(<span class="variable">$msg</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>示例3：云数据库 Memcache 与 MySQL 数据库结合使用</p>
<figure class="highlight php"><table><tr><td class="code"><pre><span class="line"><span class="variable">$connect</span> = <span class="keyword">new</span> Memcached; <span class="comment">//声明一个新的memcached链接</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_COMPRESSION, <span class="literal">false</span>);<span class="comment">//关闭压缩功能</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_BINARY_PROTOCOL, <span class="literal">true</span>);<span class="comment">//使用binary二进制协议</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setOption(Memcached::OPT_TCP_NODELAY, <span class="literal">true</span>); <span class="comment">//重要，php memcached有个bug，当get的值不存在，有固定40ms延迟，开启这个参数，可以避免这个bug</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;addServer(<span class="string">&#x27;xxxxxx.m.yyyyyyyy.ocs.aliyuncs.com&#x27;</span>, <span class="number">11211</span>);<span class="comment">//添加实例地址  端口号</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;setSaslAuthData(<span class="string">&#x27;xxxxxx&#x27;</span>, <span class="string">&#x27;my_passwd&#x27;</span>);<span class="comment">//设置OCS帐号密码进行鉴权，如已开启免密码功能，则无需此步骤</span></span><br><span class="line"><span class="variable">$user</span> = <span class="keyword">array</span>(</span><br><span class="line">   <span class="string">&quot;name&quot;</span> =&gt; <span class="string">&quot;ocs&quot;</span>,</span><br><span class="line">   <span class="string">&quot;age&quot;</span>  =&gt; <span class="number">1</span>,</span><br><span class="line">   <span class="string">&quot;sex&quot;</span>  =&gt; <span class="string">&quot;male&quot;</span></span><br><span class="line">); <span class="comment">//定义一组数组</span></span><br><span class="line"><span class="keyword">if</span>(<span class="variable">$connect</span>-&gt;get(<span class="string">&#x27;your_name&#x27;</span>))</span><br><span class="line">&#123;</span><br><span class="line">  <span class="variable">$result</span> =<span class="variable">$connect</span>-&gt;get(<span class="string">&#x27;your_name&#x27;</span>);</span><br><span class="line">  print_r(<span class="variable">$result</span>);</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">&quot;Found in OCS, get data from OCS&quot;</span>; <span class="comment">//如果获取到数据，则打印此数据来源于OCS</span></span><br><span class="line">  <span class="keyword">exit</span>;  </span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">&quot;Return code:&quot;</span>, <span class="variable">$connect</span>-&gt;getResultCode();</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">&quot;Retucn Message:&quot;</span>, <span class="variable">$connect</span>-&gt;getResultMessage ();<span class="comment">//抛出code返回码</span></span><br><span class="line">  <span class="variable">$db_host</span>=<span class="string">&#x27;zzzzzz.mysql.rds.aliyuncs.com&#x27;</span>; <span class="comment">//数据库地址</span></span><br><span class="line">  <span class="variable">$db_name</span>=<span class="string">&#x27;my_db&#x27;</span>;         <span class="comment">//database name</span></span><br><span class="line">  <span class="variable">$db_username</span>=<span class="string">&#x27;db_user&#x27;</span>;    <span class="comment">//数据库用户名</span></span><br><span class="line">  <span class="variable">$db_password</span>=<span class="string">&#x27;db_passwd&#x27;</span>;<span class="comment">//数据库用户密码</span></span><br><span class="line">  <span class="variable">$connection</span>=mysql_connect(<span class="variable">$db_host</span>,<span class="variable">$db_username</span>,<span class="variable">$db_password</span>);</span><br><span class="line">  <span class="keyword">if</span> (!mysql_select_db(<span class="variable">$db_name</span>, <span class="variable">$connection</span>))</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">&#x27;Could not select database&#x27;</span>; <span class="comment">//数据库连接不成功则抛出错误信息</span></span><br><span class="line">    <span class="keyword">exit</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="variable">$sql</span> = <span class="string">&quot;SELECT name,age,sex FROM test1 WHERE name = &#x27;ocs&#x27;&quot;</span>;</span><br><span class="line">  <span class="variable">$result</span> = mysql_query(<span class="variable">$sql</span>, <span class="variable">$connection</span>);</span><br><span class="line">  <span class="keyword">while</span> (<span class="variable">$row</span> = mysql_fetch_assoc(<span class="variable">$result</span>))</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="variable">$user</span> = <span class="keyword">array</span>(</span><br><span class="line">      <span class="string">&quot;name&quot;</span> =&gt; <span class="variable">$row</span>[<span class="string">&quot;name&quot;</span>],</span><br><span class="line">      <span class="string">&quot;age&quot;</span>  =&gt; <span class="variable">$row</span>[<span class="string">&quot;age&quot;</span>],</span><br><span class="line">      <span class="string">&quot;sex&quot;</span>  =&gt; <span class="variable">$row</span>[<span class="string">&quot;sex&quot;</span>],</span><br><span class="line">    );</span><br><span class="line">    <span class="variable">$expire</span> = <span class="number">5</span>; <span class="comment">//设置数据在缓存中的过期时间</span></span><br><span class="line">    test(<span class="variable">$connect</span>-&gt;set(<span class="string">&#x27;your_name&#x27;</span>,<span class="variable">$user</span>,<span class="variable">$expire</span>), <span class="literal">true</span>, <span class="string">&#x27;Set cache failed&#x27;</span>); <span class="comment">//写入OCS缓存</span></span><br><span class="line">  &#125;</span><br><span class="line">  mysql_free_result(<span class="variable">$result</span>);</span><br><span class="line">  mysql_close(<span class="variable">$connection</span>);</span><br><span class="line">&#125;</span><br><span class="line">print_r(<span class="variable">$connect</span>-&gt;get(<span class="string">&#x27;your_name&#x27;</span>)); <span class="comment">//打印出  获取到的数据</span></span><br><span class="line"><span class="keyword">echo</span> <span class="string">&quot;Not Found in OCS,get data from MySQL&quot;</span>; <span class="comment">//确认从数据库获取的数据</span></span><br><span class="line"><span class="variable">$connect</span>-&gt;quit();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"><span class="variable">$val</span>, <span class="variable">$expect</span>, <span class="variable">$msg</span></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(<span class="variable">$val</span>!= <span class="variable">$expect</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Exception</span>(<span class="variable">$msg</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<hr>
<h3 id="【踩坑】"><a href="#【踩坑】" class="headerlink" title="【踩坑】"></a>【踩坑】</h3><p>尝试配置的时候，设置好 阿里云 memcache 参数，发现返回一个错误：UNKNOWN READ FAILURE7</p>
<p>查了一晚上，也没什么结果，第二天一看发现，配置的IP白名单有问题。</p>
<p>因为购买 memcache 的时候，绑定了专有网络，但是我在绑定 IP 白名单的时候却用到了外网IP，所以导致了读错误。</p>
<p>后面修改白名单后，也是顺利解决了这个问题。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">沙屿沫</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.shayvmo.cn/2019/08/30/memcache/">http://blog.shayvmo.cn/2019/08/30/memcache/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.shayvmo.cn" target="_blank">指尖改变世界</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/memcached/">memcached</a></div><div class="post_share"><div class="social-share" data-image="/images/7e3483ec4f7dedd5a30f0e7fee1635b921.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2019/09/02/redis-basic/"><img class="prev-cover" src= "" data-lazy-src="/images/redis/redis.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Redis基础入门</div></div></a></div><div class="next-post pull-right"><a href="/2019/08/30/php-basic-1/"><img class="next-cover" src= "" data-lazy-src="/images/php.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">php常量以及数据类型</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/images/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">沙屿沫</div><div class="author-info__description">科技始终来源于人性</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">74</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">42</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/shayvmo"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">生活就像海洋，只有意志坚强的人才能到达彼岸。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90%E8%B8%A9%E5%9D%91%E3%80%91"><span class="toc-number">1.</span> <span class="toc-text">【踩坑】</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/06/05/webman-route-annotation/" title="webman 框架 注解路由插件"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="webman 框架 注解路由插件"/></a><div class="content"><a class="title" href="/2023/06/05/webman-route-annotation/" title="webman 框架 注解路由插件">webman 框架 注解路由插件</a><time datetime="2023-06-05T07:04:07.000Z" title="发表于 2023-06-05 15:04:07">2023-06-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/29/nginx-reload-not-effect/" title="windows服务器重载nginx配置无效"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="windows服务器重载nginx配置无效"/></a><div class="content"><a class="title" href="/2023/05/29/nginx-reload-not-effect/" title="windows服务器重载nginx配置无效">windows服务器重载nginx配置无效</a><time datetime="2023-05-29T08:03:45.000Z" title="发表于 2023-05-29 16:03:45">2023-05-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/24/php-aes/" title="前后端接口传输AES加密"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="前后端接口传输AES加密"/></a><div class="content"><a class="title" href="/2023/05/24/php-aes/" title="前后端接口传输AES加密">前后端接口传输AES加密</a><time datetime="2023-05-24T07:00:39.000Z" title="发表于 2023-05-24 15:00:39">2023-05-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/16/yar-demo/" title="Yar拓展，实现PHP的RPC服务"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Yar拓展，实现PHP的RPC服务"/></a><div class="content"><a class="title" href="/2022/08/16/yar-demo/" title="Yar拓展，实现PHP的RPC服务">Yar拓展，实现PHP的RPC服务</a><time datetime="2022-08-16T09:30:43.000Z" title="发表于 2022-08-16 17:30:43">2022-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/15/my-online-log/" title="线上日志系统"><img src= "" data-lazy-src="/images/code.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="线上日志系统"/></a><div class="content"><a class="title" href="/2022/08/15/my-online-log/" title="线上日志系统">线上日志系统</a><time datetime="2022-08-15T09:03:01.000Z" title="发表于 2022-08-15 17:03:01">2022-08-15</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/images/7e3483ec4f7dedd5a30f0e7fee1635b921.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2023 By 沙屿沫</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="http://www.beian.miit.gov.cn/" target="_blank" rel="noopener"><img class="icp-icon" src= "" data-lazy-src="/images/icp.png"><span>粤ICP备18133330号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="false" async="async"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>